/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  sqlite3_handler.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2025年04月29日)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "2025年04月29日 09时47分18秒"
 *                 
 ********************************************************************************/

#include "sqlite3_handler.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static sqlite3 *db = NULL;


//数据库初始化
int db_init(const char *db_name)
{
    char 	*errmsg = NULL;
    int		rc = sqlite3_open(db_name, &db);
    if(rc != SQLITE_OK)
	{
        log_error("Cannot open database: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    const char *sql = "CREATE TABLE IF NOT EXISTS records ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                      "time TEXT NOT NULL, "
                      "device_id TEXT NOT NULL, "
                      "temperature REAL NOT NULL);";

    rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) 
	{
        log_error("Create table failed: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -2;
    }

    return 0;
}


//插入数据
int db_insert_record(const char *time, const char *device_id, double temperature)
{
    char sql[512];
    snprintf(sql, sizeof(sql),
             "INSERT INTO records (time, device_id, temperature) VALUES ('%s', '%s', %f);",
             time, device_id, temperature);

    char *errmsg = NULL;
    int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK)
	{
        log_error("Insert record failed: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }

    return 0;
}

//关闭数据库
void db_close(void)
{
    if (db) 
	{
        sqlite3_close(db);
        db = NULL;
    }
}
